/**
 * 
 */
define(function(require) {
	var comm = require('sdk/server');
	require('sdk/common');
	var bdMapData = JSON.parse(appcan.ls.val('bdMapData'));
	//重新定义html字号
	if (/Android (\d+\.\d+)/.test(navigator.userAgent)) {
      var version = parseFloat(RegExp.$1);
      var winWidth = Math.min($('body').width(),360);
      if (version /*< 4.4*/) {
        var phoneScale = winWidth / 640;
        var rootSize = parseInt(phoneScale * 100) + 'px';
        document.documentElement.style.fontSize = rootSize;
      }
    }
	if (!bdMapData || !bdMapData['lng'] || !bdMapData['lat']) {
		return alert('bdMap参数缺失');
	}
	//console.log(bdMapData.lat)
	var map, userMark;
	var openMap = function(refresh){
		if(refresh && map){
			bdMapData = JSON.parse(appcan.ls.val('bdMapData'));
			if(userMark){
				map.removeOverlay(userMark);
			}
		}else{
			map = new BMap.Map("mapView");
		}

		var paintMap = function(){
			//console.log(bdMapData.lng)
			var point = new BMap.Point(bdMapData.lng, bdMapData.lat);
			map.centerAndZoom(point, appcfg.plugin.bdmap.zoomLeval);
			userMark = new BMap.Marker(point);
			map.addOverlay(userMark);
			appcan.loading.hide();
			point=null;
		}
		if(bdMapData['loctype']=='gps'){
			appcan.loading.show('坐标转换');
			$.ajax({
				url: 'http://api.map.baidu.com/geoconv/v1/',
				dataType: 'json',
				cache:false,
				data: {
					ak: appcfg.plugin.bdmap.key,
					coords: bdMapData.lng + ',' + bdMapData.lat,
					output: 'json'
				},
				success: function(res) {
					if(res.status==0){
						bdMapData.lng=res.result[0].x;
						bdMapData.lat=res.result[0].y;
						paintMap();
					}else{
						appcan.loading.hide();
						console.log(res.status)
						appcan.window.openToast('baiduMap geoconv API错误,code:'+res.status,2000,5);
					}
				}
			})
		}else{
			paintMap();
		}
	}

	window.refresh = function(){
		openMap(true);
	};

	appcan.ready(function() {
		if(window.BMap){
			openMap();
		}else{
			appcan.getScript('http://api.map.baidu.com/getscript?v=2.0&ak=' + appcfg.plugin.bdmap.key, function() {
				appcan.loading.show('地图加载中');
				openMap();
			});
		}
		
	});
});